package com.youth.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youth.ClientEntity.UserEntity;
import com.youth.commonutils.*;
import com.youth.servicebase.exceptionhandler.GlobalException;
import com.youth.userservice.entity.UcenterMember;
import com.youth.commonutils.LoginInfo;
import com.youth.userservice.entity.vo.LoginVo;
import com.youth.userservice.entity.vo.RegisterVo;
import com.youth.userservice.entity.vo.SearchObj;
import com.youth.userservice.entity.vo.StudentVo;
import com.youth.userservice.mapper.UcenterMemberMapper;
import com.youth.userservice.service.UcenterMemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2022-10-27
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {


    private static final String USER_AVATAR = "\n" +
            "https://youth-file.oss-cn-chengdu.aliyuncs.com/2023/11/14/6bc9c81048c6446a9465635173bcb5c3dsm.jpg";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UcenterMemberMapper ucenterMemberMapper;

    /*实现用户注册的接口
     * 采用手机号+密码的方式注册
     * */
    @Override
    public R userRegister(RegisterVo registerVo) {
        /*对用户注册信息判空*/
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String nickname = registerVo.getNickname();
        Integer sex = registerVo.getSex();
        if (Objects.isNull(mobile) || Objects.isNull(sex)
                || Objects.isNull(password) || Objects.isNull(nickname)
        ) {
            throw new GlobalException(20005, "注册信息不能为空");
        }
        /*判断用户参数是否存在及合法*/

        /*判断用户是否已注册：手机号校验*/
        LambdaQueryWrapper<UcenterMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UcenterMember::getMobile, mobile);
        if (count(queryWrapper) != 0) {
            throw new GlobalException(20005, "该用户已注册");
        }
        /*注册用户*/
        UcenterMember member = new UcenterMember();
        member.setPassword(MD5.encrypt(password));   //用户密码加密后再写入数据库
        member.setSex(sex);
        member.setNickname(nickname);
        member.setMobile(mobile);
        member.setAvatar(USER_AVATAR);      // 添加默认头像，用户可以在个人中心修改
        member.setOpenMoney("100.00");
        save(member);
        return R.ok();
    }

    public static void main(String[] args) {
        System.out.println(MD5.encrypt("123456"));
    }

    /*实现用户登录的方法*/
    @Override
    public String userLogin(LoginVo loginVo) {
        if (StringUtils.isEmpty(loginVo.getMobile()) || StringUtils.isEmpty(loginVo.getPassword())) {
            throw new GlobalException(20001, "请填写好你的手机号和密码");
        }
        String mobile = loginVo.getMobile();
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        UcenterMember ucenterMember = baseMapper.selectOne(wrapper);
        if (ucenterMember == null) {
            throw new GlobalException(20001, "该用户没有注册，请前往注册");
        }
        if (ucenterMember.getIsDisabled()) {
            throw new GlobalException(20001, "该用户已经被禁用，请联系管理员");
        }
        /*先把输入的密码进行加密之后，再和数据库里面的密码进行对比*/
        if (StringUtils.equals(ucenterMember.getPassword(), MD5.encrypt(loginVo.getPassword()))) {
            /*生成token:同时将用户的id和昵称封装进去*/
            String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
            /*将token存放到redis里面，并设置过期时间*/
            redisTemplate.opsForValue().set(ucenterMember.getNickname(), jwtToken, 24, TimeUnit.HOURS);
            // 将用户信息放入threadLocal
            UserHolder.saveUser(new UserDto(ucenterMember.getId(), ucenterMember.getNickname(),ucenterMember.getAvatar()));
            return jwtToken;
        } else {
            throw new GlobalException(20001, "用户密码错误，请重新输入");
        }
    }


    /*根据用户id获取用户登录信息*/
    @Override
    public R getLoginInfo(String memberIdByJwtToken) {
        UcenterMember ucenterMember = baseMapper.selectById(memberIdByJwtToken);
        LoginInfo vo = BeanCopyUtils.copyBean(ucenterMember, LoginInfo.class);
        return R.ok().data("ucenterMember", vo);
    }

    /*根据memberId获取member的name(误删-huang)*/
    @Override
    public String ByIdGetName(String memberId) {
        UcenterMember member = baseMapper.selectOne(new QueryWrapper<UcenterMember>().eq("id", memberId).select("nickname"));
        return member.getNickname();
    }

    /*根据用户id获取用户信息，远程调用*/
    @Override
    public UserEntity ByIdGetUser(HashMap<String, String> map) {
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(map.get("userId"))) {
            wrapper.eq("id", map.get("userId"));
        }
        if (!StringUtils.isEmpty(map.get("userName"))) {
            wrapper.like("nickname", map.get("userName"));
        }
        if (!StringUtils.isEmpty(map.get("userPhone"))) {
            wrapper.like("mobile", map.get("userPhone"));
        }
        UcenterMember ucenterMember = baseMapper.selectOne(wrapper);
        if (ucenterMember == null) {
            return null;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(ucenterMember, userEntity);
        return userEntity;
    }

    /*根据用户id和金额去扣减金额-huang-远程*/
    @Override
    public boolean subtractMoney(String userId, String money) {
        boolean flag = ucenterMemberMapper.subtractMoney(userId, money);
        return flag;
    }

    @Override
    public R pageList(Long pageNum, Long pageSize, SearchObj searchObj) {
        String name = searchObj.getName();
        Date beginTime = searchObj.getBeginTime();
        Date endTime = searchObj.getEndTime();
//        判断查询条件是否为空
        LambdaQueryWrapper<UcenterMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(name), UcenterMember::getNickname, name);
//        查询时间是否为空
        queryWrapper.between(Objects.nonNull(beginTime) && Objects.nonNull(endTime),
                UcenterMember::getGmtCreate, beginTime, endTime);
        Page<UcenterMember> memberPage = new Page<>(pageNum, pageSize);
        IPage<UcenterMember> res = page(memberPage, queryWrapper);
        /*将records封装结果*/
        List<StudentVo> rows = BeanCopyUtils.copyBeanToList(res.getRecords(), StudentVo.class);
        long total = res.getTotal();
        /*封装结果*/
        return R.ok().data("rows", rows).data("total", total);
    }

    @Override
    public R removeStudent(String id) {
        /*清除学生关联的订单信息*/
        /*清除学生收藏的课程信息*/
        /*清除该学生发表的评论*/
        return R.ok();
    }

    @Override
    public R changeDisabledStatus(String id, Boolean isDisabled) {
        /*判断修改的状态*/
        int disableType = isDisabled ? 0 : 1;
        /*调用mapper处理*/
        baseMapper.disableStudent(id, disableType);
        return R.ok();
    }

    /*更新学生信息*/
    @Override
    public R updateUserInfo(RegisterVo registerVo) {
        /*这里还是需要对密码进行加密*/
        String password = MD5.encrypt(registerVo.getPassword());
        if(!StringUtils.isEmpty(password)){
            registerVo.setPassword(password);
        }
        /*调用自己编写的sql*/
        baseMapper.updateUserInfo(registerVo);
        return R.ok();
    }


}
